﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using LMSemir.DAC;
using LMSemir.Common;
using LMSemir.Entity;
using LMSemir.Backstage.Common;

namespace LMSemir.Backstage
{
    public partial class Category : BasePage
    {
        protected string strTotalCount = "暂无";
        protected string strPaging = string.Empty;
        protected string Source = string.Empty;
        protected string startTime = string.Empty;
        protected string endTime = string.Empty;
        protected string userName = string.Empty;
        protected string strTAuthor = string.Empty;
        protected string strTMobile = string.Empty;

        private int pageIndex = 1;
        private int pageSize = 20;
        private int totalCount = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    //clear cookie for first request
                    this.Request.Cookies.Clear();
                    this.Request.Cookies.Remove("sl_source");
                    this.Request.Cookies.Remove("sl_status");
                    this.Request.Cookies.Remove("sl_category");
                    string strOP = WebUtils.GetPramaValue("op", "");
                    string urlParam = string.Empty;
                    this.userName = Session["uname"] == null ? "管理员" : Session["uname"].ToString();

                    this.pageIndex = WebUtils.GetPramaValue("page", 1);
                    this.pageSize = WebUtils.GetPramaValue("ps", 20);

                    int param = WebUtils.GetPramaValue("q", 0);

                    int strSource = WebUtils.GetFormValue("sl_source", 0) == 0 ? WebUtils.GetPramaValue("source", 0) : WebUtils.GetFormValue("sl_source", 0);

                    int strStatus = WebUtils.GetFormValue("sl_status", 0) == 0 ? WebUtils.GetPramaValue("st", 0) : WebUtils.GetFormValue("sl_status", 0);
                    int strCategory = WebUtils.GetFormValue("sl_category", 0) == 0 ? WebUtils.GetPramaValue("cate", 0) : WebUtils.GetFormValue("sl_category", 0);
                    this.startTime = string.IsNullOrEmpty(WebUtils.GetFormValue("startTime", this.startTime)) ? WebUtils.GetPramaValue("startts", "") : WebUtils.GetFormValue("startTime", this.startTime);

                    this.endTime = string.IsNullOrEmpty(WebUtils.GetFormValue("endTime", this.endTime)) ? WebUtils.GetPramaValue("endts", "") : WebUtils.GetFormValue("endTime", this.endTime);

                    string strTeeName = string.IsNullOrEmpty(WebUtils.GetFormValue("teeName", "")) ? WebUtils.GetPramaValue("ta", "") : WebUtils.GetFormValue("teeName", "");

                    this.Source = TEEUtil.WriteSourceName(param);

                    string strMobile = string.IsNullOrEmpty(WebUtils.GetFormValue("mobile", "")) ? WebUtils.GetPramaValue("tm", "") : WebUtils.GetPramaValue("mobile", "");

                    string urlParams = string.Format("&source={0}&st={1}&cate={2}&startts={3}&endts={4}&ta={5}&tm={6}", strSource, strStatus, strCategory, this.startTime.Trim(), this.endTime.Trim(), strTeeName, strMobile);

                    this.strTAuthor = strTeeName;
                    this.strTMobile = strMobile;

                    string tempStartTime = Convert.ToDateTime(this.startTime == "" ? DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd") : this.startTime).ToString("yyyy-MM-dd");
                    string tempEndTime = Convert.ToDateTime(this.endTime == "" ? DateTime.Now.ToString("yyyy-MM-dd") : this.endTime).ToString("yyyy-MM-dd");

                    DataTable dt = TeeDataAccess.GetTeeListBySearch(strMobile, tempStartTime, tempEndTime, strSource,
                        strStatus, strCategory, strTeeName, this.pageIndex, this.pageSize, out this.totalCount);

                    this.strTotalCount = totalCount.ToString();
                    this.repTeeList.DataSource = dt;
                    this.repTeeList.DataBind();

                    if (!string.IsNullOrEmpty(strOP))
                    {
                        if (strOP == "export")
                        {
                            this.repeaterToExecl(dt, "LMSemir");
                        }
                    }
                    //绑定分页样式
                    int pageCount = (int)Math.Ceiling((double)totalCount / this.pageSize);
                    this.strPaging = TEEUtil.GeneratePager(this.pageIndex, this.pageSize, pageCount, totalCount, "category.aspx", urlParams);
                }
                catch (Exception ex)
                {
                    LogUtil.GetInstance().WriteDebugLog("error:Category.aspx=>" + ex.Message);
                }
            }

        }

        private void repeaterToExecl(DataTable dt, string exportFileName)
        {
            this.Response.Clear();
            //获取或设置一个值，该值指示是否缓冲输出，并在完成处理整个响应之后将其发送
            this.Response.Buffer = true;
            //获取或设置输出流的HTTP字符集
            this.Response.Charset = "GB2312";
            //将HTTP头添加到输出流
            this.Response.AppendHeader("Content-Disposition", "attachment;filename=" + exportFileName + "" + DateTime.Now.Date.ToString("yyyyMMddHHmm") + ".xls");
            //获取或设置输出流的HTTP字符集
            this.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            //获取或设置输出流的HTTP MIME类型
            this.Response.ContentType = "application/ms-excel";
            System.IO.StringWriter onstringwriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter onhtmltextwriter = new System.Web.UI.HtmlTextWriter(onstringwriter);
            StringWriter sw = this.GetStringWriter(dt);

            HtmlTextWriter htw = new HtmlTextWriter(sw);

            string html = sw.ToString().Trim();
            Response.Output.Write(html);
            Response.Flush();
            Response.End();
        }
        //将datatable中的数据进行组装，比如添加列头（这样excel文件中第一行就看到列头名称） 
        private StringWriter GetStringWriter(DataTable dt)
        {
            StringWriter sw = new StringWriter();

            sw.Write("编号 " + "\t ");
            sw.Write("日期" + "\t ");
            sw.Write("姓名 " + "\t ");
            sw.Write("手机 " + "\t ");
            sw.Write("邮箱 " + "\t ");
            sw.Write("地址 " + "\t ");

            sw.Write(sw.NewLine);
            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    sw.Write(dr["tid"].ToString() + "\t ");
                    sw.Write(dr["TCreateTS"].ToString() + "\t ");
                    sw.Write(dr["tauthor"].ToString() + "\t ");
                    sw.Write(dr["tmobile"].ToString() + "\t ");
                    sw.Write(dr["temail"].ToString() + "\t ");
                    sw.Write(dr["taddress"].ToString() + "\t ");

                    sw.Write(sw.NewLine);
                }
            }
            sw.Close();
            sw.Dispose();
            return sw;
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            //base.VerifyRenderingInServerForm(control);
        }
    }
}